package middleware

import (
	"github.com/gin-gonic/gin"
	"jwgin/utils/jw"
	"net/http"
)

func Jwt() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		tokenString := ctx.GetHeader("Authorization")
		if tokenString == "" {
			ctx.JSON(http.StatusOK, gin.H{"code": 401, "msg": "请先登录"})
			ctx.Abort()
			return
		}

		token, claims, err := jw.ParseToken(tokenString)
		if err != nil || !token.Valid {
			ctx.JSON(http.StatusOK, gin.H{"code": 401, "msg": "认证失败"})
			ctx.Abort()
			return
		}
		ctx.Set("UserID", claims.UserId)
		ctx.Set("RoleID", claims.Role)
		ctx.Set("RoleAccount", claims.Account)
	}
}
